//
//  PrescriptionOrderController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/29.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
/// 处方订单
class PrescriptionOrderController: BaseViewController {
    
    private var viewModel = PrescriptionOrderViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "处方订单"
    }
    
    override func makeUI() {
        super.makeUI()
        
        emptyView.configure(with: UIImage(named: "empty_drugs"), title: "您还没有购买药品哦~")
        emptyView.refreshClosure = { [weak self] in
            self?.resetEmptyView()
        }
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalTo(view.safeAreaLayoutGuide).priority(.low)
            make.bottom.equalToSuperview()
        }
    }
    
    override func bindViewModel() {
        super.bindViewModel()
        
        viewModel.updateClosure = { [weak self] code in
            self?.endRefresh()
            if code == .success {
                self?.updateUI()
            }
        }
        
        viewModel.changeClosure = { [weak self] in self?.loadData() }
    }

    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.backgroundColor = .background
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 1))
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.mj_header = refreshHeader(action: #selector(loadData))
        tableView.mj_header?.beginRefreshing()
        tableView.mj_footer = refreshFooter(action: #selector(loadMore))
        
        tableView.register(PrescriptionOrderCell.nibForCell(),
                           forCellReuseIdentifier: PrescriptionOrderCell.reuseIdentifier())
        
        return tableView
    }()
}

extension PrescriptionOrderController {
    private func updateUI() {
        if !viewModel.hasMore {
            tableView.mj_footer?.endRefreshingWithNoMoreData()
        }
        tableView.isHidden = viewModel.showEmptyView
        emptyView.isHidden = !viewModel.showEmptyView
        
        tableView.reloadData()
    }
    
    private func resetEmptyView() {
        tableView.isHidden = false
        emptyView.isHidden = true
        
        setupRefresh()
    }
    
    private func setupRefresh() {
        tableView.mj_header?.beginRefreshing()
    }
    
    private func endRefresh() {
        tableView.mj_header?.endRefreshing()
        tableView.mj_footer?.endRefreshing()
    }
    
    @objc private func loadData() {
        tableView.mj_footer?.resetNoMoreData()
        viewModel.loadData()
    }
    
    @objc private func loadMore() {
        viewModel.loadData(true)
    }
}

// MARK: - DataSource && Delegate
extension PrescriptionOrderController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRows
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PrescriptionOrderCell.reuseIdentifier(),
                                                 for: indexPath) as! PrescriptionOrderCell
        cell.delegate = self
        let viewModel = viewModel.viewModel(for: indexPath)
        cell.bind(to: viewModel)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return viewModel.cellHeight(at: indexPath)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let viewModel = viewModel.viewModel(for: indexPath)
        pushOrderDetailVC(with: viewModel)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView()
        header.backgroundColor = .clear
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return viewModel.headerHeight
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
}

// MARK: - PrescriptionOrderCellCellDelegate

extension PrescriptionOrderController: PrescriptionOrderCellCellDelegate {
    func pay(_ cell: PrescriptionOrderCell) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        let viewModel = viewModel.viewModel(for: indexPath)
        pushOrderPayVC(with: viewModel)
    }
    
    func cancel(_ cell: PrescriptionOrderCell) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        
        AlertTool.showAlert(self, title: "取消订单", message: "您确定要取消订单吗？", sureTitle: "确定", cancelTitle: "再想想", type: .double, sureHandler: { _ in
            self.changeOrderStatus(.canceled, at: indexPath)
        })
    }
    
    func applyRefund(_ cell: PrescriptionOrderCell) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        
        AlertTool.showAlert(self, title: "申请退药", sureTitle: "确定", cancelTitle: "取消", type: .double, sureHandler: { _ in
            self.changeOrderStatus(.applyRefund, at: indexPath)
        })
    }
    
    func checkLogistics(_ cell: PrescriptionOrderCell) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        
        let viewModel = viewModel.viewModel(for: indexPath)
        
        pushCheckLogisticsVC(with: viewModel)
    }
    
    func confirmReceive(_ cell: PrescriptionOrderCell) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        
        changeOrderStatus(.completed, at: indexPath)
    }
    
    func cancelRefund(_ cell: PrescriptionOrderCell) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        
        AlertTool.showAlert(self, title: "取消退药", sureTitle: "确定", cancelTitle: "取消", type: .double, sureHandler: { _ in
            self.changeOrderStatus(.cancelRefund, at: indexPath)
        })
    }
    
    func inputExpressNumber(_ cell: PrescriptionOrderCell) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        
        let viewModel = viewModel.viewModel(for: indexPath)
        
        let vc = PrescriptionOrderTrackingNumberController(id: viewModel.prescriptionId)
        navigationController?.pushViewController(vc, animated: true)
        vc.handleClosure = { [weak self] in self?.loadData() }
    }
    
    private func pushOrderDetailVC(with viewModel: PrescriptionOrderCellViewModel) {
        let vc = PrescriptionOrderDetailController(orderId: viewModel.orderId)
        navigationController?.pushViewController(vc, animated: true)
        vc.updateClosure = { [weak self] in self?.loadData() }
    }
    
    private func pushOrderPayVC(with viewModel: PrescriptionOrderCellViewModel) {
        let orderStatusVc = PrescriptionOrderPayController(orderId: viewModel.orderId)
        orderStatusVc.handlerClosure = setupRefresh
        navigationController?.pushViewController(orderStatusVc, animated: true)
    }
    
    private func pushCheckLogisticsVC(with viewModel: PrescriptionOrderCellViewModel) {
        let vc = PrescriptionOrderLogisticsController(with: viewModel.expressNum)
        navigationController?.pushViewController(vc, animated: true)
    }
    
    private func changeOrderStatus(_ status: PrescriptionOrderStatus, at indexPath: IndexPath) {
        viewModel.changePrescriptionOrderStatus(status, at: indexPath)
    }
}
